import React, { useState, useEffect } from "react";
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Tabs,
  Table,
  Spin,
} from "antd";
import { upadataField, getDetail, getSqlDetail } from "../api";

// const { Option } = Select
const { TabPane } = Tabs;

const UpdateForm = (props) => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [listData, setListData] = useState([]);
  const [sqlData, setSqlData] = useState([]);

  const [sqlColumns, setSqlColumns] = useState([]);

  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    getDetail(paylaod).then((res) => {
      if (res.code === 0) {
        setListData(res.data);
        // form.setFieldsValue({ ...res.data, ...data })
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  // 详情 sql
  const getSqlDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    getSqlDetail(paylaod).then((res) => {
      if (res.code === 0) {
        setSqlData(res.data);
        form.setFieldsValue({ ...res.data });
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  useEffect(() => {
    setSqlColumns([]);
    if (type === "updata" && visible === true) {
      getDetailData();
      getSqlDetailData();
    } else {
      form.resetFields();
    }
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = (values) => {
    const hide = message.loading("正在查询");
    setLoading(true);
    const requirement = values.requirement
      ? ` where ${values.requirement}`
      : "";

    const paylaod = {
      comms: `select ${values.fields} from ${sqlData.tableName}${requirement}`,
      current: 1,
      pageSize: 10,
      firstcolumn: sqlData.firstcolumn,
      dataSourceId: sqlData.dataSourceId,
      pri: sqlData.pri,
      type: "1",
      dataUnitId: sqlData.dataUnitId,
    };
    upadataField(paylaod).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        const col = [];
        const fields = values.fields.split(",") || [];
        fields.map((item) => {
          const obj = {
            title: item,
            dataIndex: item,
            key: item,
            width: 100,
          };
          col.push(obj);
          return "";
        });
        setSqlColumns(col);

        // onCancel(false)
        // onSuccess()
      } else {
        message.error(res.msg || "修改失败，请重试");
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then((values) => {
      const columns = [];
      updataData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  // 页签切换
  const tabChange = () => {};

  const columns = [
    {
      title: "列名",
      dataIndex: "columnName",
      key: "columnName",
      width: 100,
    },
    {
      title: "类型",
      dataIndex: "columnType",
      key: "columnType",
      width: 100,
    },
    {
      title: "允许为空",
      dataIndex: "isNullable",
      key: "isNullable",
      width: 100,
    },
    {
      title: "columnKey",
      dataIndex: "columnKey",
      key: "columnKey",
      width: 100,
    },
    {
      title: "备注",
      dataIndex: "momo",
      key: "momo",
    },
  ];

  return (
    <>
      <Drawer
        getContainer={false}
        width={940}
        title={type === "updata" ? "修改" : "添加"}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <div style={{ marginBottom: 10 }}>表名称：{sqlData.tableName}</div>
          <Tabs onChange={tabChange} type="card">
            <TabPane tab="数据结构" key="1">
              <Table
                columns={columns}
                dataSource={listData}
                bordered
                size="middle"
                pagination={false}
                rowKey={(record) => record.columnName}
              />
            </TabPane>
            <TabPane tab="数据预览" key="2">
              <Form {...formItemLayout} name="control-ref" form={form}>
                <div style={{ marginBottom: 5 }}>select</div>
                <Form.Item label="" name="fields">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
                <div style={{ marginBottom: 5 }}>
                  from{" "}
                  <span style={{ fontWeight: "bold" }}>
                    {sqlData.tableName}
                  </span>{" "}
                  where
                </div>
                <Form.Item label="" name="requirement">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
              </Form>
              <Button
                type="primary"
                onClick={sendData}
                style={{ marginBottom: 10 }}
              >
                执行
              </Button>
              <Table
                columns={sqlColumns}
                dataSource={[]}
                bordered
                size="middle"
                pagination={false}
                scroll={true}
                rowKey={(record) => record.columnName}
              />
            </TabPane>
          </Tabs>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateForm;
